<template>
  <d2-container>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <div class="d2-breadcrumb">
        <el-breadcrumb-item>角色权限树编辑</el-breadcrumb-item>
      </div>
    </el-breadcrumb>
    <el-tree
      ref="tree"
      :data="data"
      show-checkbox
      node-key="id"
      :default-expanded-keys="[]"
      :default-checked-keys="roleInfo.roleMenus"
      :props="defaultProps"
    >
    </el-tree>
    <br />
    <el-button type="primary" @click="add">保存</el-button>
  </d2-container>
</template>

<script>
export default {
  name: "",
  data() {
    return {
      id: this.$route.params.id,
      data: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      roleMenus: [],
      roleInfo: {},
    };
  },
  methods: {
    add() {
      let arr = this.$refs.tree.getCheckedNodes();
      arr = arr.map((ele) => {
        return ele.id;
      });

      let params = {
        perIds: arr,
        roleId: this.id,
      };
      console.log("提交内容：", params);
      this.$axios.post("/sysRoleMenu/add", params).then((result) => {
        console.log("响应", result);

        if (result.code == 200) {
          this.$message.success("操作成功");
          this.$router.push("/systemAdmin/role");
        } else {
          this.$message.error(result.data.msg);
        }
      });
    },
    getInfo() {
      this.$axios.post("/sysMenu/treeSelect").then((result) => {
        console.log("响应", result);
        if (result) {
          this.data = result.data;
        } else {
          this.$message.error(result.data.msg);
        }
      });

      //获取角色详情
      this.$axios
        .post("/sysRole/getOneRole", { roleId: this.id })
        .then((result) => {
          console.log("角色", result);
          if (result) {
            this.roleInfo = {
              ...result.data,
              roleMenus: result.data.roleMenus.map((ele) => {
                return ele.menuId;
              }),
            };
          } else {
            this.$message.error(result.data.msg);
          }
        });

      //寻找默认节点
    },
  },
  mounted() {
    this.getInfo();
  },
};
</script>

<style scoped lang="scss">
.item-box {
  position: relative;
  width: 30%;
  .item-delete {
    position: absolute;
    right: 80px;
    top: -45px;
  }
}
.card-box {
  display: flex;
  flex-wrap: wrap;
}
</style>
